package cm309.BookingSystem.tm.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.PreparedStatement;

import java.sql.SQLException;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cm309.BookingSystem.common.Common;
import cm309.BookingSystem.common.MyConnection;
import cm309.BookingSystem.tm.model.Trainer;
import cm309.BookingSystem.web.Action;




public class UpdateTMAction implements Action {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		MyConnection con=new MyConnection();
		try {
			
			//Long oldtrainerIDnum;
			//set the Trainer
			Trainer t=new Trainer();
			//oldtrainerIDnum=Long.parseLong(con.getOneField(
			//		"Select TrainerID from BK_TM_TRAINER order by TrainerID DESC"));
			
			
			//t.setTrainerID(Long.toString(oldtrainerIDnum));
			t.setTrainerID(request.getParameter("trainerID"));
			t.setTrainerName(request.getParameter("trainerName"));
			t.setTrainerGender(request.getParameter("trainerGender").charAt(0));
			t.setTrainerAge(Integer.parseInt(request.getParameter("trainerAge")));
			t.setClassification(request.getParameter("classification"));
			
			//update
			PreparedStatement ps=con.getPS(
					"UPDATE BK_TM_TRAINER SET TRAINERNAME=? , TRAINERGENDER=?" +
					",TRAINERAGE=?,CLASSIFICATION=? WHERE TRAINERID=?");
			ps.setString(1, t.getTrainerName());
		    ps.setString(2,Character.toString(t.getTrainerGender()));
			ps.setInt(3,t.getTrainerAge());
			ps.setString(4,t.getClassification());
			ps.setString(5,t.getTrainerID());
			int count=ps.executeUpdate();
			if (count!=1) {
				throw new RuntimeException("Trainer no found");
			}
			
			con.commit();
			con.PSclose();
			
			 //redirect to the show product!
			PrintWriter w = response.getWriter();
		
			w.println(Common.beanToJson(t));
			  			
		} catch (SQLException e) {

			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			con.close();
		}

	}

}
